#include "apinetwork.h"
#include "network.h"

apiNetwork::apiNetwork(Network *network, QObject *parent) : _network(network), QObject(parent)
{
	connect(&_network->getTcpClient(), SIGNAL(connected(QHostAddress &)), this, SLOT(handleConnect(QHostAddress&)));
	connect(&_network->getTcpClient(), SIGNAL(disconnected(QHostAddress &)), this, SLOT(handleDisconnect(QHostAddress&)));
}

apiNetwork::~apiNetwork()
{
}

quint16								apiNetwork::connectTo(const std::string &ip, const std::string &port)
{
	qDebug() << "Connecting to " << QString().fromStdString(ip) << ":" << QString().fromStdString(port);
	return _network->ConnectToServer(ip, port);
}

void								apiNetwork::removeClient(quint16 id)
{
	_network->getTcpClient().removeClient(id);
}

bool								apiNetwork::isInside(quint16 id)
{
	return _network->getTcpClient().isInside(id);
}

bool								apiNetwork::isInside(QHostAddress& ip)
{
	return _network->getTcpClient().isInside(ip);
}

void								apiNetwork::handleConnect(QHostAddress &ip)
{
	emit connected(ip);
}

void								apiNetwork::handleDisconnect(QHostAddress &ip)
{
	emit disconnected(ip);
}

QHostAddress 						apiNetwork::getIp(quint16 id)
{
	return _network->getTcpClient().getIp(id);
}

quint16								apiNetwork::getId(QHostAddress &ip)
{
	return _network->getTcpClient().getId(ip);
}

void								apiNetwork::sendToTcp(Packet &pkg, quint16 id)
{
	qDebug() << "Send packet to TCP socket" << id;
	_network->getTcpClient().sendPacket(&pkg, id);
}

void								apiNetwork::sendToUdp(Packet &pkg, quint16 id)
{
	//qDebug() << "Send packet to UDP socket (not implemented)" << id;
	if (isInside(id))
		_network->getUdpServer().sendPacket(&pkg, getIp(id), 4244);
}